package com.umeox.moto.mqtt;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Environment;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Random;

public class Utils {

    public static boolean isAvailable(Context context) {
        boolean ret = false;
        if (null != context) {
            ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            if (null != cm) {
                NetworkInfo info = cm.getActiveNetworkInfo();
                if (null != info) {
                    ret = info.isAvailable() && info.isConnectedOrConnecting();
                }
            }
        }
        return ret;
    }


    /**
     * 在min和max之间取一个随机数
     */
    public static int getRandom(int min, int max){
        Random random = new Random();
        int s = random.nextInt(max) % (max - min + 1) + min;
        return s;

    }

    public static String parseRequestId(String topic) {
        int index = topic.lastIndexOf("/");
        return topic.substring(index + 1);
    }


    public static void saveMqttLog( String content) {

//        if (!BuildConfig.LOG_SAVA) {
//            return;
//        }

        final String message =  DateUtils.formatDateTime(System.currentTimeMillis())+" "+content;
        AsyncTask.execute(() -> {
            //创建一个带缓冲区的输出流
            String state = Environment.getExternalStorageState();
            if (state.equals(Environment.MEDIA_MOUNTED)) {
                String sdPath = Environment.getExternalStorageDirectory().getAbsolutePath();
                String logPath = sdPath + "/Dev/DataProvider/log/";
                File file = new File(logPath);
                FileOutputStream fos = null;
                OutputStreamWriter writer = null;
                try {
                    if(!file.exists()){
                        file.mkdirs();
                    }
                    File logFile = new File(file,"mqtt_log.txt");
                    fos = new FileOutputStream(logFile,true);
                    writer = new OutputStreamWriter(fos, "utf-8");
                    writer.write(message);
                    writer.write("\n");

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (writer != null) {
                            writer.close();
                        }

                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
}
